<template>
  <div class="personalCenter details user-details" v-cloak>
    <div class="personal-main">
      <el-form
        :label-position="labelPosition"
        :model="formData"
        :rules="rules"
        :hide-required-asterisk="way!='update' && handle!='new'"
        ref="formData"
        label-width="100px"
        class="add-user-form"
        size="small"
      >
       
        <el-form-item label="编号：">
          <el-input :disabled="true" v-model="formData.code" placeholder="自动编码"></el-input>
        </el-form-item>
        <el-form-item label="姓名:" prop="name">
          <p v-if="way != 'update'">{{formData.name}}</p>
          <el-input
            v-else
            class="add-input"
            type="text"
            v-model="formData.name"
            maxlength="16"
            placeholder="请输入16位以内的姓名"
            @keyup.native="replace(formData.name,formData,'name')"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <p v-if="way != 'update'">{{formData.mobile}}</p>
          <el-input
            v-else
            maxlength="11"
            class="add-input"
            v-model="formData.mobile"
            :disabled="handle=='see'"
            @keyup.native="replace(formData.mobile,formData,'mobile')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户头像:">
          <img :src="formData.headUrl || default_head" class="headeImg" v-if="way != 'update'" />
          <el-upload
            v-else
            class="avatar-uploader"
            :show-file-list="false"
            action="1"
            :before-upload="beforeUpload"
            :http-request="uploadFile1"
          >
            <img v-if="formData.headUrl" :src="formData.headUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="职位：" prop="type">
          <el-select
            :disabled="way != 'update'"
            v-model="formData.type"
            placeholder="请选择"
            style="width: 100%;"
            @change="onChangeType"
          >
            <el-option
              v-for="item in typeArray"
              :key="item.typeId"
              :value="item.typeId"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行业经验：" prop="experience" v-if="formData.type">
          <el-input :disabled="way != 'update'" v-model="formData.experience" maxlength="15" @keyup.native="onCheckNumber"></el-input>
        </el-form-item>
        <el-form-item label="员工照片:"  v-if="formData.type">
          <img :src="formData.employeeHeadUrl" class="headeImg" v-if="way != 'update'" />
          <el-upload
            v-else
            class="avatar-uploader"
            :show-file-list="false"
            action="1"
            :before-upload="beforeUpload"
            :http-request="uploadImg"
          >
            <img v-if="formData.employeeHeadUrl" :src="formData.employeeHeadUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row style="width: 650px" v-if="formData.type == '1111111111'">
          <el-form-item label="技师介绍：" prop="remark">
            <el-input
              :disabled="way != 'update'"
              class="textContent"
              type="textarea"
              v-model="formData.remark"
              maxlength="200"
              placeholder="200字以内"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-form-item label="角色:">
          <div class="role-list-wrap">
            <div class="el-transfer-panel" v-if="!mRole">
              <p class="el-transfer-panel__header">
                <label class="el-checkbox">
                  <span class="el-checkbox__label">角色列表</span>
                </label>
              </p>
              <div class="el-transfer-panel__body">
                <div class="el-transfer-panel__filter el-input el-input--small el-input--prefix">
                  <input
                    type="text"
                    v-model="roleKey"
                    autocomplete="off"
                    placeholder="请输入搜索内容"
                    class="el-input__inner"
                    clearable
                  />
                  <span class="el-input__prefix">
                    <i class="el-input__icon el-icon-search"></i>
                  </span>
                </div>
                <div
                  role="group"
                  aria-label="checkbox-group"
                  class="el-checkbox-group el-transfer-panel__list is-filterable"
                  v-if="formData.list.length>0"
                >
                  <label
                    v-for="(item, index) in formData.list.filter(data => !roleKey || data.roleName.toLowerCase().includes(roleKey.toLowerCase()))"
                    :key="index"
                    role="checkbox"
                    aria-checked="true"
                    class="el-checkbox el-transfer-panel__item is-checked"
                  >
                    <span class="el-checkbox__label">
                      <span v-text="item.roleName"></span>
                    </span>
                  </label>
                </div>
                <p
                  class="el-transfer-panel__empty"
                  style="text-align: center!important;"
                  v-if="formData.list.length<1"
                >无数据</p>
              </div>
            </div>
            <el-transfer
              style="text-align: left; display: inline-block"
              v-else-if="roleList"
              v-model="selectRole"
              :titles="['可选角色', '已选角色']"
              :button-texts="['删除', '添加']"
              filterable
              :props="propObj"
              :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
              :data="roleList"
              :filter-method="filterMethod"
            >
              <span slot-scope="{ option }">{{ option.roleName }}</span>
            </el-transfer>
          </div>
        </el-form-item>
      </el-form>
      <div class="personal-btn">
        <template v-if="way =='look' && !mRole">
          <el-button type="primary" @click="editDetails()" v-if="setRole('修改')">修改信息</el-button>
          <el-button type="primary" @click="mRoleBtn()" v-if="setRole('分配角色')" key="mRoleBtn">角色分配</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="cancle()" plain key="1">取消</el-button>
          <el-button type="primary" @click="saveForm()">保存信息</el-button>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import default_head from "assets/images/default_head.png";
import util from "@/util";
import { mapState } from "vuex";
import md5 from "js-md5";
import Cookies from "js-cookie";
import {
  findRoleList,
  saveOrUpdateUser,
  saveOrUpdateUserRole,
  findUserInfo2,
  uploadFile,
  getFile,
  findUnselectedRole,
  defaultPassword,
  findEmployeeTypeList
} from "@/api";
export default {
  data() {
    const checkMobile = (rule, value, callback) => {
      if (!util.validMobilePhone(value)) {
        return callback(new Error("手机号格式不正确 "));
      } else {
        callback();
      }
    };
    const checkNewPassw = (rule, value, callback) => {
      if (!util.validNumber(value)) {
        return callback(new Error("密码必须为数字"));
      } else {
        callback();
      }
    };
    const validSpecialSymbol = (rule, value, callback) => {
      if (!util.validSpecialSymbol(value)) {
        return callback(new Error("此处只能输入汉字、字母和数字！"));
      } else {
        callback();
      }
    };
    const validChineseAndLetter = (rule, value, callback) => {
      if (util.validChineseAndLetter(value)) {
        return callback(new Error("此处只能输入汉字、字母！"));
      } else {
        callback();
      }
    };
    return {
      ting: false,
      default_head: default_head,
      roleKey: "",
      handle: "",
      userId: "",
      dialogVisible: false,
      way: "", //look => 查看  update => 修改
      labelPosition: "right",
      mRole: false, //修改角色
      rules: {
        // userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
        //   {validator: validSpecialSymbol, trigger: 'blur'},
        //   { max: 10, message: '长度不能超过10个字符', trigger: 'blur' }
        // ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { validator: validChineseAndLetter, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        experience: [{
          required: true, message: "请输入行业经验", trigger: "blur"
        }],
        remark: [{
          required: true, message: "请输入技师介绍", trigger: "blur"
        }]
      },
      roleItem: "",
      rulesBox: {
        password: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur"
          },
          { validator: checkNewPassw, trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur"
          },
          { validator: checkNewPassw, trigger: "blur" }
        ]
      },
      modifyPassw: {
        password: "",
        newPassword: ""
      },
      formData: {
        status: true,
        userName: "",
        name: "",
        password: "******",
        mobile: "",
        headUrl: "",
        list: [],
        code: "",
        experience: "",
        remark: "",
        type: '',
        employeeHeadUrl:''
      },
      roleList: [],
      selectRole: [],
      propObj: {
        key: "roleId",
        lable: "roleName"
      },
      pageNum: "1",
      pageSize: "10000",
      typeArray: [],
    };
  },
  computed: mapState({
    power: "power",
    userIdSelf: state => state.userId,
    merchantId: "merchantId",
    linkName: "linkName"
  }),
  mounted() {
  
    this.order()
    this.handle = util.getQuery("handle");

    this.way = this.handle == "see" ? "look" : "update";
    if (this.handle == "new") {
      this.getRoles();
      this.mRole = true;
    } else {
      this.mRole = false;
      this.userId = util.getQuery("userId");
      if (this.handle == "see") {
        this.getDetails();
      }
    }
  },
  // mounted() {},
  watch: {},
  methods: {
      onChangeType(val){
        this.formData.experience = ''
        this.formData.remark = ''
      },
    replace(value, obj, key) {
      let that = this;
      let event = event || window.event;
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(value, obj, key);
        }, 100);
      } else {
        that.validItem(value, obj, key);
      }
    },
       // 获取下拉列表信息
    order() {
      findEmployeeTypeList().then(res => {
        let obj=[{
          code: "",
          name: "无",
          typeId: "",
          remark: "",
          status: 0
        }]
        res.data.list=obj.concat(res.data.list)
        this.typeArray = res.data.list;
      });
    },
    validItem(value, obj, key) {
      let res = "";
      switch (key) {
        case "userName":
          res = util.replaceSpecialSymbol(value);
          res = util.replaceEmpty(res);
          break;
        case "name":
          res = util.replaceChineseAndLetter(value);
          break;
        case "mobile":
          res = util.replaceNumber(value);
          break;
      }
      this.$set(obj, key, res);
    },
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    getDetails() {
      let that = this;
      // let id = this.businessId? this.businessId: this.merchantId
      let data = {
        merchantId: this.merchantId,
        userId: that.userId
      };
      findUserInfo2(data).then(res => {
        let data = res.data;
        if (+res.code == 200) {
          that.formData.name = data.linkName;
          that.formData.mobile = data.mobile;
          that.formData.headUrl = data.headUrl;
          that.formData.list = data.roleList;
          that.formData.userName = data.userName;
          that.formData.type = data.employeeType;
          that.formData.experience = data.experience;
          that.formData.remark = data.remark;
          that.formData.code = data.code,
          that.formData.employeeHeadUrl=data.employeeHeadUrl
        }
      });
    },
    getRoles() {
      let that = this;
      let data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        merchantId: this.merchantId
      };
      findRoleList(data).then(res => {
        if (+res.code == 200) {
          that.roleList = res.data.roleList;
        }
      });
    },
    //修改基础信息和角色
    saveForm() {
      let that = this;
      if (that.mRole && that.handle == "see") {
        that.allotRole(util.getQuery("userId"));
        return;
      }
      
      this.$refs.formData.validate(valid => {
        if (valid) {
          let data = {
            userId: util.getQuery("userId"),
            userName: that.formData.userName,
            mobile: that.formData.mobile,
            password: md5(defaultPassword),
            merchantId: that.merchantId,
            linkName: that.formData.name,
            headUrl: that.formData.headUrl,
            experience: that.formData.experience,
            remark: that.formData.remark,
            typeId: that.formData.type,
            employeeHeadUrl:that.formData.employeeHeadUrl
          };
          saveOrUpdateUser(data).then(res => {
            if (+res.code == 200) {
              if (data.userId == that.userIdSelf) {
                if (that.linkName != data.linkName) {
                  that.$store.commit("SET_LINKNAME", data.linkName);
                  Cookies.set(
                    process.env.COOKIE_NAME + "_linkName",
                    data.linkName
                  );
                }
                if (that.headUrl != data.headUrl) {
                  that.$store.commit("SET_HEADURL", data.headUrl);
                  let userInfo = JSON.parse(
                    Cookies.get(process.env.COOKIE_NAME + "_userInfo")
                  );
                  userInfo.headUrl = data.headUrl;
                  Cookies.set(
                    process.env.COOKIE_NAME + "_userInfo",
                    JSON.stringify(userInfo)
                  );
                }
              }
              if (that.mRole) {
                if (that.selectRole.length < 1) {
                  that.openTips2(res.data.userId);
                  return;
                }
                that.allotRole(res.data.userId);
              } else {
                that.openTips("提交成功！", "success");
                that.getDetails();
                that.way = "look";
              }
              // this.$refs.formData.resetFields();
            }
          });
        } else {
          return false;
        }
      });
    },
    mRoleBtn() {
      let that = this;
      that.roleList = [];
      that.selectRole = [];
      let data = {
        userId: util.getQuery("userId"),
        merchantId: that.merchantId
      };
      that.formData.list.forEach(val => {
        that.selectRole.push(val["roleId"]);
      });
      findUnselectedRole(data).then(res => {
        if (+res.code == 200) {
          that.roleList = res.data.roleList.concat(that.formData.list);
          that.mRole = true;
        }
      });
    },
    allotRole(id) {
      let that = this;
      let roles = "";
      that.selectRole.forEach(val => {
        roles += `${val},`;
      });
      let data = {
        userId: id,
        roleIds: roles,
        merchantId: this.merchantId
      };

      saveOrUpdateUserRole(data).then(res => {
        if (+res.code == 200) {
          if (that.handle == "new") {
            that.openTips2(id);
          } else {
            that.openTips("角色分配成功！", "success");
            that.getDetails();
            that.way = "look";
            that.mRole = false;
          }
          roles = "";
          that.selectRole = [];
        } else {
          that.openTips(res.msg, "error");
        }
      });
    },
    editDetails() {
      let that = this;
      that.way = "update";
    },
    cancle() {
      let that = this;
      if (that.handle == "new") {
        util.routerTo("/operate-management/user-management");
        return;
      }
      that.getDetails();
      if (that.mRole) {
        that.selectRole = [];
        that.mRole = false;
        return;
      }
      if (that.way == "update") {
        that.way = "look";
        this.$refs.formData.resetFields();
      }
    },
    //上传图片
    uploadFile1(param) {
      let that = this;
      let fileObj = param.file;
      let data = new FormData();
      data.append("file", fileObj);
      data.append("projectName", fileObj.name);
      uploadFile(data).then(res => {
        if (res.code == 200) {
          that.formData.headUrl = `${getFile}?id=${res.data.id}`;
        } else {
          this.$message({
            message: "图片上传失败",
            type: "error"
          });
        }
      });
    },
    uploadImg(param) {
      let that = this;
      let fileObj = param.file;
      let data = new FormData();
      data.append("file", fileObj);
      data.append("projectName", fileObj.name);
      uploadFile(data).then(res => {
        if (res.code == 200) {
          that.formData.employeeHeadUrl = `${getFile}?id=${res.data.id}`;
        } else {
          this.$message({
            message: "图片上传失败",
            type: "error"
          });
        }
      });
    },
    beforeUpload(file) {
      let isJPG =
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg";
      let isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像只能为png/jpg/jpeg格式");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //修改密码
    closePasswBox() {
      let that = this;
      that.dialogVisible = false;
      this.$refs.modifyPassw.resetFields();
    },
    submitPassw() {
      var that = this;
      this.$refs.modifyPassw.validate(valid => {
        if (valid) {
          let data = {
            userId: that.formData.mobile,
            password: that.modifyPassw.password,
            newPassword: that.modifyPassw.newPassword
          };
          data.type = that.userIdSelf == that.userId ? 1 : 2;
          platformUpdPwd(data).then(res => {
            if (+res.code == 200) {
              that.openTips("密码修改成功！", "success");
              that.dialogVisible = false;
              this.$refs.modifyPassw.resetFields();
            } else {
              that.openTips(res.msg, "error");
            }
          });
        } else {
          return false;
        }
      });
    },
    openTips(tip, type) {
      this.$message({
        message: tip,
        type: type
      });
    },
    openTips2(id) {
      this.openTips("用户新增成功！", "success");
      this.way = "look";
      this.mRole = false;
      this.handle = "see";
      this.userId = id;
      this.getDetails();
      util.routerTo("/operate-management/user-management/user-details", {
        handle: "see",
        userId: id
      });
    },
    filterMethod(query, item) {
      return item.roleName.indexOf(query) > -1;
    },
    onCheckNumber() {
      this.formData.experience = util.replaceNumber(this.formData.experience)
    }
  }
};
</script>
<style lang='less'>
.details {
  .avatar-uploader {
    text-align: left;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: auto;
    height: 100px;
    display: block;
  }
}
</style>
<style lang='less' scoped>
[v-cloak] {
  display: none !important;
}
.personalCenter {
  .personal-main {
    background: #fff;
    padding: 20px 40px;
    .el-form {
      width: 625px;
      .el-form-item {
        margin-bottom: 10px;
        padding: 6px 0;
      }
    }
    p {
      text-align: left !important;
    }
    .personal-password {
      padding-right: 30px;
    }
    .headeImg {
      width: auto;
      height: 100px;
      display: block;
      float: left;
    }
    .personal-btn {
      padding-top: 30px;
      padding-bottom: 20px;
    }
  }
}
</style>
